﻿using System.IO;
using System.Reflection;
using System.Windows;
using Bookvar.UI;
using Microsoft.Scripting;

namespace Bookvar.Console
{
    public partial class ConsoleControl
    {
        private const string MainTopicName = "MainTopic";

        internal static DynamicTopic MainTopic
        {
            get
            {
                ScriptModule module;
                if (ScriptDomainManager.CurrentManager.TryGetScriptModule("__main__", out module))
                {
                    object mainTopic;
                    if ( module.TryGetVariable( MainTopicName, out mainTopic ) )
                    {
                        return mainTopic as DynamicTopic;
                    }
                }
                return null;
            }
        }

        public static readonly DependencyProperty MindMapPanelProperty =
            DependencyProperty.Register( "MindMapPanel", typeof ( MindMapPanel ), typeof ( ConsoleControl ),
                                         new FrameworkPropertyMetadata( default( MindMapPanel ), OnMindMapPanelChanged ) );

        public MindMapPanel MindMapPanel
        {
            get { return (MindMapPanel) GetValue( MindMapPanelProperty ); }
            set { SetValue( MindMapPanelProperty, value ); }
        }

        public ConsoleControl()
        {
            InitializeComponent();
        }

        private static void OnMindMapPanelChanged( DependencyObject sender, DependencyPropertyChangedEventArgs args )
        {
            ConsoleControl consoleControl = (ConsoleControl) sender;
            MindMapPanel newPanel = (MindMapPanel) args.NewValue;
            FileInfo file = new FileInfo( Assembly.GetExecutingAssembly().Location );
            consoleControl.console.LanguageEngine.ScriptEngine.ExecuteFileContent(
                Path.Combine(file.DirectoryName, "init.py"),
                consoleControl.console.LanguageEngine.CurrentModule );
            consoleControl.console.LanguageEngine.CurrentModule.SetVariable(
                MainTopicName, new DynamicTopic( newPanel.MainTopicPresenter ) );
        }
    }
}